<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel" order="top" btnalign="right">
        <a-form :form="form" class="hearr">
            <a-form-item style="display: none">
                <a-input v-decorator="['id']"/>
                <a-input v-decorator="['type']"/>
            </a-form-item>
            <a-row>
                <a-col :span="20">
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.name','权限名称')">
                        <rx-input-i18n :placeholder="i18n('form.name','名称')" :isDecorator="true"
                                       v-decorator="['name', {rules: [{required: true, message: i18n('form.name','名称','input')}]}]"/>
                    </a-form-item>


                </a-col>
                <a-col :span="4">
                    <a-form-item :label-col="{ span: 11 }" :wrapper-col="{ span: 6 }" :label="i18n('form.enable','启用')"
                                 style="margin-left: 20px">
                        <a-checkbox
                            :placeholder="i18n('form.enabled','是否启用')"
                            :checked="mdl.enable"
                            @change="onChange"
                            v-decorator="['enable', { rules: [{ required: false, message: i18n('form.enabled','是否启用') }] }]"
                        ></a-checkbox>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row>
                <a-col :span="20">
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
                                 :label="i18n('form.classification','分类')">
                        <rx-textboxlist ref="valueList">
                            <a-icon type="setting" @click="openDialog"/>
                        </rx-textboxlist>
                    </a-form-item>
                </a-col>
                <a-col :span="4"></a-col>
            </a-row>
        </a-form>
        <!--  -->
        <div class="content_in">
            <div class="contentleft">
                <div class="contentleft_hear">{{ i18n('auth.authConfig', '权限配置') }}</div>
                <a-menu mode="inline" theme="light" class="contentleftamenu">
                    <template v-for="(list, index) in authRightData">
                        <a-sub-menu :key="list.id" v-if="list.children">
                          <span slot="title">
                            <span :title="i18nApi(list.type+'Auth',list.typeName)">{{
                                    i18nApi(list.type + 'Auth', list.typeName)
                                }}</span>
                          </span>
                            <a-menu-item
                                :title="i18nApi(typlis.type+'Auth',typlis.typeName)"
                                style="padding-left: 40px"
                                @click="editlist(typlis, index, index1)"
                                :key="typlis.id"
                                v-for="(typlis, index1) in list.children"
                            >{{ i18nApi(typlis.type + 'Auth', typlis.typeName) }}
                            </a-menu-item
                            >
                        </a-sub-menu>
                        <a-menu-item v-else :key="list.id" @click="editlist(list, index)">
                            {{ i18nApi(list.type + 'Auth', list.typeName) }}
                        </a-menu-item>
                    </template>
                </a-menu>
            </div>
            <div class="contentright">
                <div class="conhert"><span>{{ $ti18('rxList.config', '配置') }}</span></div>
                <a-form :form="form">
                    <div class="myHeader">
                        <a-radio style="width: 120px" @change="onChangeAll" v-model="allType">
                            {{ i18n('auth.owner', '所有人') }}
                        </a-radio>
                        <a-radio style="width: 120px" @change="onChangeNone" v-model="noneType">
                            {{ i18n('auth.none', '无权限') }}
                        </a-radio>
                        <a-radio style="width: 120px" @change="onChangeShowList" v-model="showList">
                            {{ i18n('auth.custom', '自定义') }}
                        </a-radio>
                    </div>
                    <template v-if="showList">
                        <ul class="container-box">
                            <li v-for="(dataObj, index) in typeList">
                                <form-user-or-group @change="aliskt" ref="preview" :dataObj="dataObj"></form-user-or-group>
                            </li>
                        </ul>
                    </template>
                </a-form>
            </div>
        </div>
    </rx-dialog>
</template>
<script>
import SysAuthSettingApi from '@/api/system/core/sysAuthSetting'
import {BaseForm, RxDialog, RxGrid, RxTextBoxList, Dialog, Util, RxInputI18n} from "@lowcode/jpaas-common-lib"
import authSettings from '@/api/system/core/authSetting'
import DialogBox from '@/assets/js/DialogBox'

import FormPermissionApi from '@/api/form/core/formPermission'
import ARow from 'ant-design-vue/es/grid/Row'
import ACol from 'ant-design-vue/es/grid/Col'
import FormUserOrGroup from '@/views/modules/form/core/formPermission/FormUserOrGroup'

export default {
    name: 'SysAuthSettingEdit',
    mixins: [BaseForm],
    props: ['type'],
    components: {
        RxDialog,
        RxGrid,
        RxTextBoxList,
        ACol,
        Util,
        ARow,
        Dialog,
        FormUserOrGroup,
        RxInputI18n
    },
    data() {
        return {
            columns: [
                {
                    title: this.i18n('auth.permission', '权限'),
                    dataIndex: 'type',
                    displayField: 'typeName',
                    scopedSlots: {customRender: 'type'},
                    width: 100,
                },
                {
                    title: this.$ti18('rxList.config', '配置'),
                    dataIndex: 'setting',
                    scopedSlots: {customRender: 'setting'},
                    width: 100
                },
            ],
            authRightData: [],
            catKey: this.type,
            readKey: this.type == 'BPM' ? 'def.read' : 'read',
            values: {value: '', text: ''},
            //formuser
            showList: false,
            typeList: [],
            allType: false,
            noneType: false,
            resultData: {},
            value: '',
            index: '',
        }
    },
    watch: {
        mdl() {
            //  转换成布尔类型
            this.mdl['enable'] = JSON.parse(this.mdl.enable)
        },
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "SysAuthSetting", key);
        },
        i18nApi(name, text, key) {
            return this.$ti18(name, text, "systemApi", key);
        },
        aliskt() {
            this.getValues()
        },
        editlist(list, index, index1) {
            this.index = index
            this.index1 = index1
            this.value = list.setting
            this.getPermissionList()
        },
        onChangeAll(e) {
            if (this.allType) {
                //选择所有人，则清空所有选择
                this.noneType = false;
                this.showList = false;
            }
            this.changeType()
        },
        onChangeNone(e) {
            if (this.noneType) {
                //选择无权限，则清空所有选择
                this.allType = false;
                this.showList = false;
            }
            this.changeType()
        },
        onChangeShowList(e) {
            if (this.showList) {
                this.noneType = false;
                this.allType = false;
                if (this.attachmentType) {
                    this.attachmentList = true;
                }
            }
            this.changeType();
        },
        changeType() {
            for (var i = 0; i < this.typeList.length; i++) {
                var obj = this.typeList[i]
                obj.values = ''
                obj.names = ''
            }
            this.getValues()
        },
        getPermissionList() {
            var serf_ = this
            serf_.allType = false
            serf_.noneType = false
            serf_.showList = false
            FormPermissionApi.getPermissionList().then((res) => {
                serf_.setTypeValue(res.data)
            })
        },
        setTypeValue(data) {
            this.typeList = data
            if (!this.value || 'everyone' == this.value) {
                this.allType = true
            } else if ('none' == this.value) {
                this.noneType = true
            } else if ('custom' == this.value) {
                this.showList = true
            } else {
                var selectObj = JSON.parse(this.value)
                for (var i = 0; i < this.typeList.length; i++) {
                    var typeObj = this.typeList[i]
                    var isContinue = false
                    for (var key in selectObj) {
                        if (key == typeObj.type) {
                            typeObj.values = selectObj[key].values
                            typeObj.names = selectObj[key].names
                            typeObj.include = selectObj[key].include
                            isContinue = true
                            break
                        }
                    }
                    if (isContinue) {
                        continue
                    }
                }
                this.showList = true
            }
        },
        getValues() {
            if (this.noneType) {
                var resultData = {
                    label: this.i18n('auth.none', '无权限'),
                    value: 'none',
                }
            } else if (this.allType) {
                var resultData = {
                    label: this.i18n('auth.owner', '所有人'),
                    value: 'everyone',
                }
            } else {
                var names = []
                var typeListObj = {}
                for (var i = 0; i < this.typeList.length; i++) {
                    var typeObj = this.typeList[i]
                    if (!typeObj.names) {
                        continue
                    }
                    typeListObj[typeObj.type] = {
                        names: typeObj.names,
                        values: typeObj.values,
                        include: typeObj.include,
                    }
                    names.push(typeObj.name + ':' + typeObj.names)
                }

                if (names.length > 0) {
                    var resultData = {
                        label: names.join(','),
                        value: JSON.stringify(typeListObj),
                    }
                } else {
                    var resultData = {
                        label: this.i18n('auth.noConfig', '无配置'),
                        value: 'custom',
                    }
                }
            }
            if (this.index1 == undefined) {
                this.authRightData[this.index].setting = resultData.value
                this.authRightData[this.index].settingName = resultData.label
            } else {
                this.authRightData[this.index].children[this.index1].setting = resultData.value
                this.authRightData[this.index].children[this.index1].settingName = resultData.label
            }
        },
        openDialog() {
            var self = this
            var data = this.$refs.valueList.getValue()
            var selectedKeys = data.value.split(",");
            DialogBox.openSysTreeDialog({
                    curVm: self,
                    widthHeight: ['800px', '600px'],
                    data: {catKey: self.catKey, selectedKeys: selectedKeys},
                }, function (data) {
                    let ids = []
                    let names = []
                    for (let i = 0; i < data.length; i++) {
                        let obj = data[i]
                        ids.push(obj.treeId)
                        names.push(obj.name)
                    }
                    let value = ids.join(',')
                    //将分类名称国际化
                    let nameList = names.map(name=>self.$i18(name));

                    let text = nameList.join(',')
                    self.$refs.valueList.clearValue()
                    self.$refs.valueList.setValues({value: value, text: text}, false)
                }
            )
        },
        parseTree(arr, callback) {
            arr.forEach(item => {
                callback(item);
                if (item.children) {
                    this.parseTree(item.children, callback);
                }
            })
        },
        onload_(data) {
            let defaultRightJson = Util.deepClone(authSettings.getByType(this.catKey));
            if (!data) {
                this.mdl = Object.assign({type: this.catKey, enable: true})
                this.form.setFieldsValue(this.mdl)
                this.authRightData = defaultRightJson;
            } else {
                var sysAuthRights = data.sysAuthRights
                if (sysAuthRights) {
                    sysAuthRights.forEach(item => {
                        this.$refs.valueList.setValues({value: item.treeId, text: item.treeName}, false)
                    })
                }
                var rightJson = {};
                this.parseTree(JSON.parse(data.rightJson), function (item) {
                    rightJson[item.id] = item;
                });
                this.parseTree(defaultRightJson, function (item) {
                    let json = rightJson[item.id];
                    if (!json || json.children) {
                        return;
                    }
                    item.setting = json.setting;
                    item.settingName = json.settingName;
                });
                this.authRightData = defaultRightJson;
            }
        },
        get(id) {
            return SysAuthSettingApi.getAuthSetting(id)
        },
        save(values) {
            var data = this.$refs.valueList.getValue()
            values.treeId = data.value
            values.treeName = data.text
            values.rightJson = JSON.stringify(this.authRightData)
            return SysAuthSettingApi.saveConfigJson(values)
        },
        onChange(e) {
            this.mdl['enable'] = e.target.checked
        },
        editRecord(record, index, type) {
            if (!record[type]) return
            DialogBox.openPermissionUser(this, record[type], function (self_, data) {
                self_.setChangeValue(index, type, data, record)
            })
        },
        setChangeValue(index, type, data, record) {
            var parents = this.$refs.authRight.findRows(function (data) {
                if (data['id'] == record['parentId']) return true
            })
            var target
            if (parents.length > 0) {
                target = parents[0].children[index]
            } else {
                target = record
            }
            if (target) {
                target[type] = data.value
                target[type + 'Name'] = data.label
            }
        },
    },
}
</script>
<style>
.conhert {
    height: 40px;
    background-color: #f5f7fa;
}

.conhert span {
    float: left;
    line-height: 40px;
    margin-left: 20px;
}

.conhert button {
    width: 100px;
    float: right;
    margin-right: 20px;
}

.hearr {
    border-top: 1px solid #e6e8eb;
    padding-top: 20px;
}

.content_in {
    border-top: 1px solid #e6e8eb;
    width: 100%;
    height: calc(100% - 150px);
    overflow: hidden;
    overflow-y: auto;
}

.contentleft {
    float: left;
    border-right: 1px solid #e6e8eb;
    width: 200px;
    height: 100%;
    overflow: auto;
}

.contentleft_hear {
    line-height: 50px;
    margin-left: 28px;
}

.contentleftamenu {
    width: 150px;
    border-right: none;
    margin: auto;
}

.contentleftamenu .ant-menu-submenu-arrow {
    left: 4px !important;
}

.contentleftamenu .ant-menu-submenu-title {
    color: rgba(0, 0, 0, 0.65) !important;
}

.contentright {
    width: calc(100% - 200px);
    float: left;
    overflow: auto;
}

.myHeader {
    padding: 20px;
    margin-left: 20px;
}

.container-box {
    padding: 10px 20px;
    box-sizing: border-box;
}

.container-box > li {
    width: 100%;
    margin-right: 20px;
    padding: 10px;
    overflow: hidden;
}

.container-box > li:last-child {
    margin-right: 0;
}
</style>
